package router

import (
	"0306zk/api/client"
	"0306zk/api/enit"
	"0306zk/api/pkg"
	"0306zk/common/proto/user"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Login(c *gin.Context) {
	var data enit.User
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	login, err := client.Login(c, &user.LoginReq{
		Mobile:   data.Mobile,
		Password: data.Password,
		Code:     data.Code,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}

	claims := pkg.CustomClaims{
		ID: uint(login.Id),
	}
	token, err := pkg.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "token生成失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "用户登陆成功",
		"data": token,
	})

}

func Register(c *gin.Context) {
	var data enit.User
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	register, err := client.Register(c, &user.RegisterReq{
		Mobile:   data.Mobile,
		Password: data.Password,
		Code:     data.Code,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "用户注册成功",
		"data": register,
	})
}

func SendSms(c *gin.Context) {
	var data enit.SendSms
	if err := c.ShouldBind(&data); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	register, err := client.SendSms(c, &user.SendSmsReq{
		Mobile: data.Mobile,
		Source: data.Source,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "短信验证码发送成功",
		"data": register,
	})
}
